package com.hobart.learning.lagou.edu.IPersistence.sqlSession;

import com.hobart.learning.lagou.edu.IPersistence.config.BoundSql;
import com.hobart.learning.lagou.edu.IPersistence.pojo.Configuration;
import com.hobart.learning.lagou.edu.IPersistence.pojo.MappedStatement;
import com.hobart.learning.lagou.edu.IPersistence.utils.GenericTokenParser;
import com.hobart.learning.lagou.edu.IPersistence.utils.ParameterMapping;
import com.hobart.learning.lagou.edu.IPersistence.utils.ParameterMappingTokenHandler;
import org.apache.commons.lang3.StringUtils;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ：hobart
 * @date ：Created in 2020-11-11 0:43
 * @description：执行sql
 * @modified By：
 * @version: 1$
 */
public class SimpleExcutor implements Executor {

    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params)
            throws SQLException, NoSuchFieldException, ClassNotFoundException, IllegalAccessException,
            IntrospectionException, InstantiationException, InvocationTargetException {
        // 1. 注册驱动，获取连接
        Connection connection = configuration.getDataSource().getConnection();

        // 2.获取sql语句: select * from user where useranme = #{username} and password = #{password}
        // 转换成 select * from user where useranme = ? and password = ?
        // 并将sql 语句中 #{} 中的值 解析 存储
        String sql = mappedStatement.getSql();
        System.out.println("sql = " + sql);
        BoundSql boundSql = getBoundSql(sql);

        // 3. 获取预处理对象： preparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlTest());

        // 4. 设置参数
            // 获取 参数的 全路径
        String paramterType = mappedStatement.getParamterType();
        Class<?> paramterTypeClass = getClassType(paramterType);

        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        for (int i = 0; i < parameterMappings.size(); i ++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            String content = parameterMapping.getContent();

            // 反射
            Field declaredField = paramterTypeClass.getDeclaredField(content);

            // 暴力访问
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);

            preparedStatement.setObject(i+1, o);

        }

        // 5. 执行 sql
        ResultSet resultSet = preparedStatement.executeQuery();
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);
        List<Object> objects = new ArrayList<>();


        // 6.封装返回结果集
        while(resultSet.next()){
            Object instance = resultTypeClass.newInstance();
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i ++){
                // 字段名
                String columnName = metaData.getColumnName(i);
                // 字段的值
                Object value = resultSet.getObject(columnName);

                // 使用反射或者内省，根据数据库和实体的对应关系，完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(instance, value);
            }
            objects.add(instance);
        }

        return (List<E>) objects;
    }

    @Override
    public int insert(Configuration configuration, MappedStatement mappedStatement, Object[] params)
            throws SQLException, NoSuchFieldException, ClassNotFoundException, IllegalAccessException,
            IntrospectionException, InstantiationException, InvocationTargetException {
        // 1. 注册驱动，获取连接
        Connection connection = configuration.getDataSource().getConnection();

        // 2.获取sql语句: insert into user (id, username, password, remark) values (#{id}, #{username}, #{password}, #{remark})
        // 转换成 insert into user (id, username, password, remark) values (?, ?, ?, ?)
        // 并将sql 语句中 #{} 中的值 解析 存储
        String sql = mappedStatement.getSql();
        System.out.println("sql = " + sql);
        BoundSql boundSql = getBoundSql(sql);

        // 3. 获取预处理对象： preparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlTest());

        // 4. 设置参数
        // 获取 参数的 全路径
        String paramterType = mappedStatement.getParamterType();
        Class<?> paramterTypeClass = getClassType(paramterType);

        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        for (int i = 0; i < parameterMappings.size(); i ++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            String content = parameterMapping.getContent();

            // 反射
            Field declaredField = paramterTypeClass.getDeclaredField(content);

            // 暴力访问
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);

            preparedStatement.setObject(i+1, o);

        }

        // 5. 执行 sql
        int resultSet = preparedStatement.executeUpdate();

        return resultSet;
    }

    @Override
    public int update(Configuration configuration, MappedStatement mappedStatement, Object[] params)
            throws SQLException, NoSuchFieldException, ClassNotFoundException, IllegalAccessException,
            IntrospectionException, InstantiationException, InvocationTargetException {
        // 1. 注册驱动，获取连接
        Connection connection = configuration.getDataSource().getConnection();

        // 2.获取sql语句: update user set username = #{username}, password = #{password}, remark = #{remark} whwere id = #{id}
        // 转换成 update user set username = ?, password = ?, remark =? whwere id = ?
        // 并将sql 语句中 #{} 中的值 解析 存储
        String sql = mappedStatement.getSql();
        System.out.println("sql = " + sql);
        BoundSql boundSql = getBoundSql(sql);

        // 3. 获取预处理对象： preparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlTest());

        // 4. 设置参数
        // 获取 参数的 全路径
        String paramterType = mappedStatement.getParamterType();
        Class<?> paramterTypeClass = getClassType(paramterType);

        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        for (int i = 0; i < parameterMappings.size(); i ++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            String content = parameterMapping.getContent();

            // 反射
            Field declaredField = paramterTypeClass.getDeclaredField(content);

            // 暴力访问
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);

            preparedStatement.setObject(i+1, o);

        }

        // 5. 执行 sql
        int resultSet = preparedStatement.executeUpdate();

        return resultSet;
    }

    @Override
    public int delete(Configuration configuration, MappedStatement mappedStatement, Object[] params)
            throws SQLException, NoSuchFieldException, ClassNotFoundException, IllegalAccessException,
            IntrospectionException, InstantiationException, InvocationTargetException {
        // 1. 注册驱动，获取连接
        Connection connection = configuration.getDataSource().getConnection();

        // 2.获取sql语句: delete from user where id = #{id}
        // 转换成 delete from user where id = ?
        // 并将sql 语句中 #{} 中的值 解析 存储
        String sql = mappedStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);

        // 3. 获取预处理对象： preparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlTest());

        // 4. 设置参数
        // 获取 参数的 全路径
        String paramterType = mappedStatement.getParamterType();
        Class<?> paramterTypeClass = getClassType(paramterType);

        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        for (int i = 0; i < parameterMappings.size(); i ++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            String content = parameterMapping.getContent();

            // 反射
            Field declaredField = paramterTypeClass.getDeclaredField(content);

            // 暴力访问
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);

            preparedStatement.setObject(i+1, o);

        }

        // 5. 执行 sql
        int resultSet = preparedStatement.executeUpdate();

        return resultSet;
    }

    private Class<?> getClassType(String paramterType) throws ClassNotFoundException {
        if(StringUtils.isNotBlank(paramterType)){
            Class<?> aClass = Class.forName(paramterType);
            return aClass;
        }
        return null;
    }

    /**
     * 完成#{} 的解析：
     * 1.将#{} 使用? 进行代替
     * 2.解析出#{}里面的值进行存储
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql) {

        // 标记处理， 配置标记解析器来完成对占位符的解析工作
        ParameterMappingTokenHandler tokenHandler = new ParameterMappingTokenHandler();

        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", tokenHandler);
        // 解析出来的sql
        String parseSql = genericTokenParser.parse(sql);
        // #{}解析出来的参数名称
        List<ParameterMapping> parameterMappings = tokenHandler.getParameterMappings();

        BoundSql boundSql = new BoundSql(parseSql, parameterMappings);
        return boundSql;
    }
}
